﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;
using MediSIIM.BaseBiz;
using System.Reflection;
using System.Windows.Forms;
using System.Text;
using MediSIIM.Message;
using MediSIIM.Compression;
using System.Xml.Serialization;
using System.Xml;
using ZMQ;
using System.Runtime.InteropServices;
using TradeTest;

namespace SIIMWeb.YIBAO
{
    public class YIBAOJK
    {
        public static T YBCall<T>(CallParam callparam, string xmlin)
        {
            var content = "";
            BZip2.Compress(xmlin, out content); ;
            var inxml = string.Format(GetXmlHead(),
                  Guid.NewGuid(),
                  DateTime.Now,
                  callparam.YLBXMC + "." + callparam.TradeName,
                  ConfigurationManager.AppSettings["Version"],
                  Encoding.UTF8.GetByteCount(content),
                  content);

            var str = "";
            var siim = MessageParser.Parse(inxml, ref str);

            var sengine = new ServiceEngine();
            sengine.ServiceInfo = new ServiceInfo { ClassName = callparam.ClassName, DllPath = callparam.BizDll };
            sengine.DBConnectionManager = DBUtil.ConnectionManager;
            sengine.LoadAssembly();
            sengine.RunService(siim, ref str);
            return DataUtil.GetObject<T>(str);
        }

        static ZMQ.Context mqContext = new Context(1);
        /// <summary>
        /// 获得消息头:[GUID、时间、消息类型、版本号、内容长度、内容]
        /// </summary>
        /// <returns></returns>
        public static string GetXmlHead()
        {
            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SIIMMessage>" +
                "  <Head>" +
                "    <MessageId>{{{0}}}</MessageId>" +
                "    <MessageDate>{1:yyyy-MM-dd HH:mm:ss}</MessageDate>" +
                "    <MessageType>{2}</MessageType>\r\n" +
                "    <Version>{3}</Version>" +
                "    <Sender>HIS</Sender>" +
                "    <Receiver>SIIM</Receiver>" +
                "  </Head>" +
                "  <Body>" + "    <Length>{4}</Length>" +
                "    <Content>{5}</Content>" +
                "  </Body>" +
                "</SIIMMessage>";
        }
        public static string ZMQCallF(string ylbxid, string jiaoyimc, string xcontent, string siimurl = "")
        {
            var content = ZMQCall(ylbxid, jiaoyimc, xcontent, siimurl);
            string path = "..\\XmlLog\\" + ylbxid;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var filename = string.Format("{0}\\{1}_OUT.{2:yyyyMMddHHmmssfff}.xml", path, jiaoyimc, DateTime.Now);
            File.WriteAllText(filename, content, Encoding.UTF8);
            return filename;
        }


        public static string ZMQCall(string ylbxid, string jiaoyimc, string xcontent, string siimurl = "")
        {
            Socket socket = null;
            if (socket == null)
            {
                socket = mqContext.Socket(SocketType.DEALER);
                if (string.IsNullOrEmpty(siimurl))
                {
                    siimurl = ConfigurationManager.AppSettings["SIIMURL"];
                }
                socket.Connect(siimurl);
            }
            string msgType = ylbxid + "." + jiaoyimc;
            string compress = string.Empty;
            BZip2.Compress(xcontent, out compress);
            //var message = string.Format(GetXmlHead(),
            //  Guid.NewGuid().ToString(), DateTime.Now, ylbxid + "." + jiaoyimc, "v2_001", Encoding.UTF8.GetByteCount(xcontent), compress);
            var message = GetHead(ylbxid + "." + jiaoyimc, "v2_001", Encoding.UTF8.GetByteCount(xcontent), compress);

            var sendstat = socket.Send("", Encoding.UTF8, SendRecvOpt.SNDMORE);
            if (sendstat == SendStatus.Sent)
            {
                sendstat = socket.Send(msgType, Encoding.UTF8, SendRecvOpt.SNDMORE);
                sendstat = socket.Send(message, Encoding.UTF8);
                var list = new List<byte>();

                string msg = "";
                foreach (var item in socket.RecvAll(Encoding.UTF8))
                {
                    msg = item;
                }
                //msg = Encoding.UTF8.GetString(list.ToArray());
                if (msg == "")
                {
                    throw new System.Exception("连接医保中间件失败");
                }
                var siimmsg = MessageParser.Parse(msg, ref msg);
                if (siimmsg == null)
                {
                    return string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><result>{0}</result>", msg);
                }
                return siimmsg.Body.Content;
            }
            else
            {
                throw new System.Exception("连接医保中间件失败");
            }
        }

        public static string GetHead(params object[] args)
        {
            var msg = new SIIMMessage();
            msg.Head = new SIIMMessageHead();
            msg.Body = new SIIMMessageBody();
            msg.Head.MessageId = Guid.NewGuid().ToString();
            msg.Head.MessageDate = DateTime.Now.ToString();
            msg.Head.Receiver = "SIIM";
            msg.Head.Sender = "HIS";
            msg.Head.MessageType = args[0].ToString();
            msg.Head.Version = args[1].ToString();
            msg.Body.Length = int.Parse(args[2].ToString());
            msg.Body.Content = args[3].ToString();

            return DataUtil.GetXml(msg);
        }
    }
}